package com.fzu.ess.sys.shiro.filter;

import com.fzu.ess.common.Const;
import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * Created by ercha on 2015/10/30.
 */
@Getter
@Setter
public class kickOutFilter extends AccessControlFilter {

    private Cache<String, String> cache;

//    private int maxSession = 1;

    private boolean kickOutAfter = false;

    private SessionManager sessionManager;

    private String kickOutUrl = "/";

    public kickOutFilter(CacheManager cacheManager, String cacheName){
        cache = cacheManager.getCache(cacheName);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        //如果没有登录，直接进行之后的流程
        if(!subject.isAuthenticated() && !subject.isRemembered()) {
            return true;
        }

        Session session = subject.getSession();
        String username = Const.CACHE_PREFIX.USERNAME + subject.getPrincipal();
        String sessionId = Const.CACHE_PREFIX.SESSION + session.getId().toString();

        String curStatus = cache.get(sessionId);
        if(curStatus == null){
            cache.put(sessionId, "1");  //1 为不踢出，0 为踢出
        }
        else if(curStatus.equals("0")){ //踢出
            cache.remove(sessionId);
            subject.logout();
            saveRequest(request);
            WebUtils.issueRedirect(request, response, kickOutUrl);
            return false;
        }

        String cacheSession = cache.get(username);
        if(cacheSession == null){
            cache.put(username, sessionId);
            return true;
        }
        else if(!cacheSession.equals(sessionId)){
            if(!kickOutAfter){
                cache.put(username, sessionId);
                cache.put(cacheSession, "0");
            }
            else{ //踢出自己
                cache.remove(sessionId);
                subject.logout();
                saveRequest(request);
                WebUtils.issueRedirect(request, response, kickOutUrl);
                return false;
            }
        }
        return true;
    }
}
